
//
//  ORUserSingleton.m
//  News
//
//  Created by rimi on 2016/12/12.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "ORUserSingleton.h"

@implementation ORUserSingleton

//解档
- (instancetype)initWithCoder:(NSCoder *)coder{
    
    self = [super init];
    if (self) {
        //给属性赋值
        self.headImageUrl = [coder decodeObjectForKey:@"headImageUrl"];
        self.username = [coder decodeObjectForKey:@"username"];
        self.accountName = [coder decodeObjectForKey:@"accountName"];
        self.accounsex = [coder decodeObjectForKey:@"accounsex"];
        self.isLogin = [[coder decodeObjectForKey:@"isLogin"] boolValue];
    }
    return self;
}

//归档
- (void)encodeWithCoder:(NSCoder *)aCoder{
    [aCoder encodeObject:self.headImageUrl forKey:@"headImageUrl"];
    [aCoder encodeObject:self.username forKey:@"username"];
    [aCoder encodeObject:self.accountName forKey:@"accountName"];
    [aCoder encodeObject:self.accounsex forKey:@"accounsex"];
    [aCoder encodeObject:@(self.isLogin) forKey:@"isLogin"];
}

//单例
+ (instancetype)sharedUserInfo{
    
    static ORUserSingleton *info = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        info = [ORUserSingleton readInfo];
    });
    return info;
}

+ (instancetype)readInfo{
    
    //沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"/userInfo.plist"];
    //解档
    ORUserSingleton *info = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    if (!info) {
        info = [[ORUserSingleton alloc]init];
    }
    return info;
}

//存到本地
- (void)save{
    
    //沙盒地址
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingString:@"/UserInfo.plist"];
    //归档
    [NSKeyedArchiver archiveRootObject:self toFile:path];
    
}

//推出
- (void)loginOut{
    
    self.username = nil;
    self.headImageUrl = nil;
    self.isLogin = NO;
    self.accountName = nil;
    self.accounsex = nil;
    [self save];
    
}

@end
